// 参考 https://www.w3school.com.cn/tags/html_ref_canvas.asp

import yellow from './yellow.jpeg';

export default class CanvasTool {
  constructor(elementId, options = {}) {
    try {
      this.canvasEle = document.getElementById(elementId);
      this.width = this.canvasEle.width = options.width || 1188;
      this.height = this.canvasEle.height = options.height || 840;
      this.context = this.canvasEle.getContext('2d');
    } catch (err) {
      console.error(`HTML Id ${elementId}: ${err}`);
    }
  }

  getWidth () {
    return this.width;
  }

  setWidth (width) {
    this.width = this.canvasEle.width = width;
  }

  getHeight () {
    return this.height;
  }

  setHeight (height) {
    this.height = this.canvasEle.height = height;
  }

  getContext () {
    return this.context;
  }

  getTextWidth (text = '文本', font = { fontSize: 16, fontName: '宋体', fontColor: 'black' }) {
    this.context.font = font.fontSize + "px " + font.fontName;
    return this.context.measureText(text).width
  }

  getDataURL () {
    const MIME_TYPE = "image/png";
    return this.canvasEle.toDataURL(MIME_TYPE, 0.1);
  }

  /**
   * 绘制文本
   * @param {object} position 文本内容与位置 text,x,y
   * @param {object} font 文本样式  fontSize,fontName,fontColor
   */
  drawText (position = { text: '文本', x: 10, y: 10 }, font = { fontSize: 12, fontName: '宋体', fontColor: 'black' }) {
    this.context.font = font.fontSize + "px " + font.fontName;
    this.context.fillStyle = font.fontColor;
    this.context.fillText(position.text, position.x, position.y);
  }

  drawLine (start = { x: 10, y: 10 }, end = { x: 10, y: 30 }) {
    this.context.beginPath();
    this.context.moveTo(start.x, start.y);
    this.context.lineTo(end.x, end.y);
    this.context.stroke();
  }

  /**
   * 绘制矩形框
   * @param {number} x 起点横坐标
   * @param {number} y 起点纵坐标
   * @param {number} width 宽度
   * @param {number} height 高度
   */
  drawRect (x = 40, y = 40, width = 150, height = 100) {
    this.context.strokeRect(x, y, width, height);
  }

  /**
   * 绘制矩形区域图片
   * @param {url} src 图片地址
   * @param {number} x 起点横坐标
   * @param {number} y 起点纵坐标
   * @param {number} width 宽度
   * @param {number} height 高度
   */
  drawImg (src = '', x = 80, y = 80, width = 100, height = 100) {
    const img = new Image();
    img.src = src || yellow;
    img.onload = () => {
      this.context.drawImage(img, x, y, width, height);
    }
  }

  clearCanvas () {
    this.context.clearRect(0, 0, this.width, this.height);
  }
}